// 3.cpp

#include "exercise.h"
#include "openGLExt.h"

GLfloat cube_vertex[] = 
{
    -1.0f, 1.0f, 1.0f,
    -1.0f, -1.0f, 1.0f,
    1.0f, -1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,
    -1.0f, 1.0f, -1.0f,
    -1.0f, -1.0f, -1.0f,
    1.0f, -1.0f, -1.0f,
    1.0f, 1.0f, -1.0f
};

GLfloat cube_color[] = 
{
    1.0f, 0.0f, 0.0f,
    1.0f, 1.0f, 0.2f,
    0.0f, 1.0f, 1.0f,
    0.0f, 0.2f, 1.0f,
    1.0f, 1.0f, 0.2f,
    1.0f, 1.0f, 1.0f,
    0.2f, 0.2f, 1.0f,
    1.0f, 1.0f, 0.2f,
};

GLushort cube_indices[] = 
{
    0, 1, 2, 3, 
    7, 6, 5, 4, 
    4, 5, 1, 0, 
    3, 2, 6, 7, 
    4, 0, 3, 7, 
    1, 5, 6, 2, 
    //0xffff,
};

class exerciseScene3 : public exerciseScene
{
public:
    virtual void setupScene();
    virtual void cleanScene();
    virtual void renderScene();
private:
    GLuint bufNames[3];
};

void exerciseScene3::setupScene()
{
    glextInitOpenglEntry15();
    glEnable(GL_DEPTH_TEST);

    // buffer: vertex, color, index
    glGenBuffers(3, bufNames);

    // vertex
    glBindBuffer(GL_ARRAY_BUFFER, bufNames[0]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cube_vertex), cube_vertex, GL_STATIC_DRAW);
    glVertexPointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0));
    glEnableClientState(GL_VERTEX_ARRAY);

    // color
    glBindBuffer(GL_ARRAY_BUFFER, bufNames[1]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cube_color), cube_color, GL_STATIC_DRAW);
    glColorPointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0));
    glEnableClientState(GL_COLOR_ARRAY);

    // index
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufNames[2]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cube_indices), cube_indices, GL_STATIC_DRAW);
    //glPrimitiveRestartIndex(0xffff);
    //glEnable(GL_PRIMITIVE_RESTART);
}

void exerciseScene3::cleanScene()
{
    glDeleteBuffers(3, bufNames);
}

void exerciseScene3::renderScene()
{
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(1.0, 2.0, 2.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-4.0, 4.0, -4.0, 4.0, -10.0, 10.0);

    glDrawElements(GL_QUADS, sizeof(cube_indices)/sizeof(*cube_indices), GL_UNSIGNED_SHORT, BUFFER_OFFSET(0));
}

exerciseScene* createScene3()
{
    return new exerciseScene3;
}